﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsBuyerTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Buyer Business Object
    /// </summary>

    public class Buyer : BOBase
    {
        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected Buyer() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the Buyer.
        /// </summary>
        public int BuyerID
        {
            get { return _buyerID; }
            set
            {
                if (_buyerID != value)
                {
                    if (OnPropertyChanging("BuyerID", _buyerID, value))
                    {
                        int oldValue = _buyerID;
                        _buyerID = value;

                        OnPropertyChanged("BuyerID", oldValue, value);
                    }
                }
            }
        }  private int _buyerID = -1;

        /// <summary>
        /// First Name.
        /// </summary>
        public string FirstName
        {
            get { return _firstname; }
            set
            {
                if (_firstname != value)
                {
                    if (OnPropertyChanging("FirstName", _firstname, value))
                    {
                        string oldValue = _firstname;
                        _firstname = value;
                        OnPropertyChanged("FirstName", oldValue, value);
                    }
                }
            }
        }  private string _firstname = null;


        /// <summary>
        /// Last Name.
        /// </summary>
        public string LastName
        {
            get { return _lastname; }
            set
            {
                if (_lastname != value)
                {
                    if (OnPropertyChanging("LastName", _lastname, value))
                    {
                        string oldValue = _lastname;
                        _lastname = value;
                        OnPropertyChanged("LastName", oldValue, value);
                    }
                }
            }
        }  private string _lastname = null;


        /// <summary>
        /// WorkPhone.
        /// </summary>
        public string WorkPhone
        {
            get { return _workphone; }
            set
            {
                if (_workphone != value)
                {
                    if (OnPropertyChanging("WorkPhone", _workphone, value))
                    {
                        string oldValue = _workphone;
                        _workphone = value;
                        OnPropertyChanged("WorkPhone", oldValue, value);
                    }
                }
            }
        }  private string _workphone = null;


        /// <summary>
        /// MobilePhone.
        /// </summary>
        public string MobilePhone
        {
            get { return _mobilephone; }
            set
            {
                if (_mobilephone != value)
                {
                    if (OnPropertyChanging("MobilePhone", _mobilephone, value))
                    {
                        string oldValue = _mobilephone;
                        _mobilephone = value;
                        OnPropertyChanged("MobilePhone", oldValue, value);
                    }
                }
            }
        }  private string _mobilephone = null;


        /// <summary>
        /// UserName.
        /// </summary>
        public string UserName
        {
            get { return _username; }
            set
            {
                if (_username != value)
                {
                    if (OnPropertyChanging("UserName", _username, value))
                    {
                        string oldValue = _username;
                        _username = value;
                        OnPropertyChanged("UserName", oldValue, value);
                    }
                }
            }
        }  private string _username = null;



        /// <summary>
        /// EmailAddress.
        /// </summary>
        public string EmailAddress
        {
            get { return _emailaddress; }
            set
            {
                if (_emailaddress != value)
                {
                    if (OnPropertyChanging("EmailAddress", _emailaddress, value))
                    {
                        string oldValue = _emailaddress;
                        _emailaddress = value;
                        OnPropertyChanged("EmailAddress", oldValue, value);
                    }
                }
            }
        }  private string _emailaddress = null;


        /// <summary>
        /// Password.
        /// </summary>
        public string Password
        {
            get { return _password; }
            set
            {
                if ( _password != value)
                {
                    if (OnPropertyChanging("Password", _password, value))
                    {
                        string oldValue = _password;
                        _password = value;
                        OnPropertyChanged("Password", oldValue, value);
                    }
                }
            }
        }  private string _password = null;



        /// <summary>
        /// ProfileURL.
        /// </summary>
        public string ProfileURL
        {
            get { return _profileURL; }
            set
            {
                if (_profileURL != value)
                {
                    if (OnPropertyChanging("ProfileURL", _profileURL, value))
                    {
                        string oldValue = _profileURL;
                        _profileURL = value;
                        OnPropertyChanged("ProfileURL", oldValue, value);
                    }
                }
            }
        }  private string _profileURL = null;


        /// <summary>
        /// AddressLine1.
        /// </summary>
        public string AddressLine1
        {
            get { return _addressline1; }
            set
            {
                if (_addressline1 != value)
                {
                    if (OnPropertyChanging("AddressLine1", _addressline1, value))
                    {
                        string oldValue = _addressline1;
                        _addressline1 = value;
                        OnPropertyChanged("AddressLine1", oldValue, value);
                    }
                }
            }
        }  private string _addressline1 = null;



        /// <summary>
        /// AddressLine2.
        /// </summary>
        public string AddressLine2
        {
            get { return _addressline2; }
            set
            {
                if (_addressline2 != value)
                {
                    if (OnPropertyChanging("AddressLine2", _addressline2, value))
                    {
                        string oldValue = _addressline2;
                        _addressline2 = value;
                        OnPropertyChanged("AddressLine2", oldValue, value);
                    }
                }
            }
        }  private string _addressline2 = null;


        /// <summary>
        /// City.
        /// </summary>
        public string City
        {
            get { return _city; }
            set
            {
                if (_city != value)
                {
                    if (OnPropertyChanging("City", _city, value))
                    {
                        string oldValue = _city;
                        _city = value;
                        OnPropertyChanged("City", oldValue, value);
                    }
                }
            }
        }  private string _city = null;


        /// <summary>
        /// State.
        /// </summary>
        public string State
        {
            get { return _state; }
            set
            {
                if (_state != value)
                {
                    if (OnPropertyChanging("State", _state, value))
                    {
                        string oldValue = _state;
                        _state = value;
                        OnPropertyChanged("State", oldValue, value);
                    }
                }
            }
        }  private string _state = null;


        /// <summary>
        /// Country.
        /// </summary>
        public string Country
        {
            get { return _country; }
            set
            {
                if (_country != value)
                {
                    if (OnPropertyChanging("Country", _country, value))
                    {
                        string oldValue = _country;
                        _country = value;
                        OnPropertyChanged("Country", oldValue, value);
                    }
                }
            }
        }  private string _country = null;


        /// <summary>
        /// ZipCode.
        /// </summary>
        public string ZipCode
        {
            get { return _zipcode; }
            set
            {
                if (_zipcode != value)
                {
                    if (OnPropertyChanging("ZipCode", _zipcode, value))
                    {
                        string oldValue = _zipcode;
                        _zipcode = value;
                        OnPropertyChanged("ZipCode", oldValue, value);
                    }
                }
            }
        }  private string _zipcode = null;



        /// <summary>
        /// SecurityQuestion.
        /// </summary>
        public string SecurityQuestion
        {
            get { return _securityquestion; }
            set
            {
                if (_securityquestion != value)
                {
                    if (OnPropertyChanging("SecurityQuestion", _securityquestion, value))
                    {
                        string oldValue = _securityquestion;
                        _securityquestion = value;
                        OnPropertyChanged("SecurityQuestion", oldValue, value);
                    }
                }
            }
        }  private string _securityquestion = null;



        /// <summary>
        /// SecurityAnswer.
        /// </summary>
        public string SecurityAnswer
        {
            get { return _securityanswer; }
            set
            {
                if (_securityanswer != value)
                {
                    if (OnPropertyChanging("SecurityAnswer", _securityanswer, value))
                    {
                        string oldValue = _securityanswer;
                        _securityanswer = value;
                        OnPropertyChanged("SecurityAnswer", oldValue, value);
                    }
                }
            }
        }  private string _securityanswer = null;





        /// <summary>
        /// Date/time at which the Buyer was created.
        /// </summary>
        public DateTime? IDCreatedOn
        {
            get { return _idcreatedon; }
            set
            {
                if (_idcreatedon != value)
                {
                    if (OnPropertyChanging("IDCreatedOn", _idcreatedon, value))
                    {
                        DateTime? oldValue = _idcreatedon;
                        _idcreatedon = value;
                        OnPropertyChanged("IDCreatedOn", oldValue, value);
                    }
                }
            }
        }  private DateTime? _idcreatedon = null;



        /// <summary>
        /// True iff the Admin has made this JobCategory Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty Buyer object.
        /// </summary>
        public static Buyer CreateNew()
        {
            Buyer obj = new Buyer();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static Buyer CreateNew(BuyerCollection collection)
        {
            Buyer obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (Buyer buyer in collection)
            {
                if (buyer.BuyerID < minVal)
                    minVal = buyer.BuyerID;
            }
            obj.BuyerID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllBuyers

        /// <summary>
        /// Returns a collection of all Buyers.
        /// </summary>
        public static BuyerCollection GetAllBuyers()
        {
            BuyerTableAdapter adapter = new BuyerTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsBuyer.BuyerDataTable tbl = adapter.GetDataByBuyerID(null);

            BuyerCollection list = new BuyerCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsBuyer.BuyerRow row in tbl.Rows)
                {
                    Buyer buyer = new Buyer();
                    RelationalToObject(buyer, row);
                    list.Add(buyer);
                }
            }

            return (list);
        }

        #endregion

        #region GetBuyerByID

        /// <summary>
        /// Returns an Buyer object for the specified 'BuyerID' or null if no Buyer with the specified parameter(s) exists.
        /// </summary>
        public static Buyer GetBuyerByID(int buyerid)
        {
            BuyerTableAdapter adapter = new BuyerTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsBuyer.BuyerDataTable tbl = adapter.GetDataByBuyerID(buyerid);

            if (tbl.Rows.Count == 1)
            {
                Buyer buyer = new Buyer();
                RelationalToObject(buyer, tbl.Rows[0]);
                return (buyer);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'Buyer' returned more than one User record.");

            return (null);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified Buyer.
        /// </summary>
        public static void Update(Buyer obj)
        {
            bool updateBuyer = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateBuyer = (obj.ObjState != ObjectState.Unchanged);

                if (!updateBuyer)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsBuyer.BuyerDataTable tbl = null;
            if (updateBuyer)
            {
                BuyerTableAdapter adapter = new BuyerTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();

                tbl = new dsBuyer.BuyerDataTable();
                dsBuyer.BuyerRow row = tbl.NewBuyerRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (BuyerID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("BuyerID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                //if ((Question == null) || (Question.Trim().Length == 0))
                //{
                //    Errors.Add(new ValidationError("Question", "Question is required.", ValidationError.Severity.Error));
                //}
                //else if (ObjState == ObjectState.Added)
                //{

                //}

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("Buyer: BuyerID={0}, UserName={1}, {2}", BuyerID, UserName));
        }

        #endregion

        #endregion

        #region Privates - None


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more Buyer objects.
    /// </summary>

    public class BuyerCollection : List<Buyer>
    {
        #region Types

        public class UserComparer : IComparer<Buyer>
        {
            public int Compare(Buyer b1, Buyer b2)
            {
                return (String.Compare(b1.UserName, b2.UserName));
            }
        }

        #endregion

        #region Public Methods

        #region FindByBuyerID

        public Buyer FindByBuyerID(int buyerID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].BuyerID == buyerID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindBuyerByUserName

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public Buyer FindBuyerByUserName(string username)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].UserName == username)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion
    }
}
